<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="head-container">
          <el-input
            v-model="filterPara.name"
            placeholder="请输入搜索关键字"
            type="primary"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @input="handleSearch"
          />
        </div>
      </el-col>
      <el-col :span="8">
        <div class="pull-right">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="refresh">刷新</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">上传</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>

      <el-table v-loading="loading" :data="files.pagedList">
        <el-table-column label="文件编号" key="id" prop="id" width="150" />
        <el-table-column label="文件名称" key="name" prop="name" width="350" />
        <el-table-column label="文件大小" key="size" prop="size" width="150" :formatter="fileSizeFormatter"/>
        <el-table-column label="创建时间" key="createTime" prop="createTime" width="200" />
        <el-table-column label="文件状态" key="hasParsed" prop="hasParsed" :formatter="hasFileParsed" width="150"/>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="handleStore(scope.row)"
              v-if="!scope.row.hasParsed"
            >存储文件数据</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewColumns(scope.row)"
              v-else
            >查看文件列信息</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
            >删除文件</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="files.pageParams.total>0"
        :total="files.pageParams.total"
        :page.sync="files.pageParams.pageNum"
        :limit.sync="files.pageParams.pageSize"
        @pagination="handlePaging"
      />
    </el-row>

    <!-- 上传文件对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body>
      <el-form ref="uploadForm" :model="dialog.uploadForm" label-width="80px">
        <el-row>
          <el-upload
            ref="upload"
            action=""
            :on-change="handleUploadChange"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
          >
            <el-button slot="trigger" size="small" type="primary" >选取文件</el-button>
<!--            <el-button size="small" type="primary" :disabled="!dialog.selected" @click="reselectFile">清空选择</el-button>-->
<!--            <div slot="tip" class="el-upload__tip">不超过500</div>-->
          </el-upload>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpload">上 传</el-button>
        <el-button @click="dialog.open=false;">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看文件列信息" :visible.sync="columnDialog.open" width="600px" append-to-body>
      <el-table :data="columnDialog.columns" border stripe style="width: 100%;">
        <el-table-column label="列名" key="name" prop="name" />
        <el-table-column label="数据类型" key="type" prop="type" />
        <el-table-column label="数据库表" key="tableName" prop="tableName" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="columnDialog.open=false;">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="存储文件数据" :visible.sync="storeDialog.open" width="800px" append-to-body class="spec-dialog">
      <el-form ref="fileTopData" :model="storeDialog.fileTopData" label-width="100px" style="height: 400px;overflow:auto">
           <el-form-item label="工作表" prop="sheetName" required>
              <el-select v-model="storeDialog.fileTopData.sheetName" placeholder="请选择工作表" @change="changeSheet">
                  <el-option
                    v-for="item in storeDialog.sheetNames"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文件名称" prop="fileName" required>
              <el-input v-model="storeDialog.fileTopData.fileName" placeholder="请输入文件名称" />
            </el-form-item>
            <el-form-item label="标题行" prop="titleLine" required>
              <el-input-number v-model="storeDialog.fileTopData.titleLine" :min="1" :max="storeDialog.fileTopData.rows-1"></el-input-number>
            </el-form-item>
            <el-form-item label="数据开始行" prop="dataStartLine" required>
              <el-input-number v-model="storeDialog.fileTopData.dataStartLine" :min="2" :max="storeDialog.fileTopData.rows"></el-input-number>
            </el-form-item>
            <el-form-item label="异常值处理" prop="handleException" required>
              <el-checkbox v-model="storeDialog.fileTopData.handleException">使用缺失值替代异常值</el-checkbox>
            </el-form-item>
            <div>
                <el-row style="margin: -10px 0 20px 0">
                    <span style="font: bold 16px sans-serif; margin: 0 20px">数据预览</span>
                    <span>最多展示前100行数据，全量数据共{{storeDialog.fileTopData.rows}}行</span>
                </el-row>
                <el-table :data="storeDialog.fileTopData.data.slice(1)" border stripe style="width: 100%;" :row-class-name="rowClassName" v-loading="storeDialog.loading">
                    <el-table-column prop="id" width="50">
                         <template slot="header">
                             <div>1</div>
                         </template>
                    </el-table-column>
                    <el-table-column v-for="(item,index) in storeDialog.fileTopData.columnNames" :key="item" :label="item" width="120">
                        <template #header="scope">
                           <div>{{item}}</div>
                           <div>
                               <el-select v-model="storeDialog.fileTopData.columnTypes[index]" placeholder="请选择数据类型" @change="(val)=>{typeChange(val,index)}">
                                    <el-option
                                        v-for="item in storeDialog.typeOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                           </div>
                        </template>
                        <template slot-scope="scope">
                           {{scope.row[index] ? scope.row[index] : 'null'}}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="parseAndStore">存 储</el-button>
        <el-button @click="storeDialog.open=false;">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {listFiles, uploadFile, getTopData, convertType, storeFileData, getColumns, deleteFile} from "@/api/manage/dataSourceFile";
  export default {
    name: "dataSourceFile",
    dicts: [],
    data() {
      return {
        loading:true,
        filterPara:{
          name:undefined,
        },
        files:{
          uploadList:[],
          originList:[],
          list:[],
          pagedList:[],
          pageParams:{
            pageNum:1,
            pageSize:10,
            total:undefined,
          },
        },
        dialog:{
          open:false,
          title:"",
          selected:false,
          uploadFiles:[],
          uploadForm:{
            file:null,
            name:null,
          },
          rules:{
            name:[
              // { required: true, message: "名称不能为空", trigger: "blur" },
            ]
          },
        },
        columnDialog: {
            open:false,
            loading: false,
            columns:[]
        },
        storeDialog: {
            open: false,
            loading: false,
            sheets: [],
            sheetNames:[],
            fileTopData: {
                fileId: undefined,
                sheetName: "",
                fileName: "",
                titleLine: 1,
                dataStartLine: 2,
                cols: 0,
                rows: 0,
                handleException: true,
                columnNames: [],
                columnTypes: [],
                data: [],
                originData: []
            },
            typeOptions: [{
                value: 'String',
                label: 'String'
            },{
                value: 'Boolean',
                label: 'Boolean'
            },{
                value: 'Float',
                label: 'Float'
            },{
                value: 'Integer',
                label: 'Integer'
            },{
                value: "Date",
                label: "Date"
            },{
                value: "Time",
                label: "Time"
            }]
        }
      }
    },
    created() {
      this.getFileList();
    },
    watch:{
      filterPara:{
        handler:function() {
          this.handleSearch();
        },
        deep:true,
      }
    },
    methods: {
      refresh(){
        this.getFileList();
        this.$modal.msgSuccess("刷新成功");
      },
      hasFileParsed(row,column) {
        return row.hasParsed ? '已存储' : '已上传';
      },
      fileSizeFormatter(row, column) {
        if (!row.hasParsed) {
            return row.size;
        } else {
            let items = row.size.split(",");
            return items[0] + "行，" + items[1] + "列"
        }
      },
      getFileList(){
        this.loading=true;
        listFiles().then(response=>{
          this.files.originList=response.data;
          this.files.pageParams.total=this.files.originList.length;
          this.files.list=response.data;
          this.loading=false;
          this.resetPaging();
        });
      },
      handleAdd(){
        this.dialog.title="上传文件";
        this.dialog.open=true;
      },
      handleSearch(){
        let newList=[];
        this.files.originList.forEach(item=>{
          if(item.name.includes(this.filterPara.name)){
            newList.push(item);
          }
        });
        this.files.list=newList;
        this.resetPaging();
      },
      resetPaging(){
        this.files.pageParams={
          pageNum:1,
          pageSize:10,
          total:undefined,
        };
        this.handlePaging();
      },
      handlePaging(){
        let params=this.files.pageParams;
        this.files.pageParams.total=this.files.list.length;
        this.files.pagedList=this.files.list.slice(
          (params.pageNum-1)*params.pageSize,
          params.pageNum*params.pageSize
        );
      },
      handleUploadChange(file,fileList){
        this.dialog.selected=true;
        if(fileList.length>1){
          fileList.splice(0,1);
        }
        if(fileList.length==1){
          this.dialog.uploadForm.file=fileList[0].raw;
        }else {
          this.dialog.uploadForm.file=fileList[0].raw;
        }
      },
      reselectFile(){

      },
      handleUpload(){
        // this.$refs["uploadForm"].validate(valid=>{
          if(this.dialog.uploadForm.file!=null){
            let formData = new FormData();
            formData.append("file", this.dialog.uploadForm.file);
            uploadFile(formData).then(response=>{
              this.$modal.msgSuccess("上传成功");
              this.dialog.open = false;
              this.getFileList();
            });
          }
        // });
      },
      handleDel(row){
        this.$modal.confirm('是否确定删除文件："' +row.name + "” ？").then(function() {
          return deleteFile({
            fileId:row.id,
          });
        }).then(response=>{
          this.$modal.msgSuccess("删除成功");
          this.getFileList();
        }).catch(() => {});
      },
      handleViewColumns(row) {
          this.columnDialog.open = true;
          this.columnDialog.loading = true;
          getColumns({fileId:row.id}).then(response=>{
              let originColumns = response.data;
              let columns = []
              for (let i = 0; i<originColumns.columns.length; i++) {
                  columns.push({
                      name: originColumns.columns[i],
                      type: originColumns.types[i],
                      tableName: originColumns.tableName
                  })
              }
              this.columnDialog.columns = columns;
              this.columnDialog.loading = false;
              console.log(this.columnDialog.columns)
          })
      },
      handleStore(row) {
          getTopData({
            fileId: row.id
          }).then(response=>{
              
              this.storeDialog.sheets = response.data.sheets
              console.log(response.data)
              this.storeDialog.sheetNames = this.storeDialog.sheets.map(function(i,index,arr){
                  let option = {}
                  option.value = i.name;
                  option.label = i.name;
                  return option;
              },this);
              this.storeDialog.fileTopData.fileId = row.id;
              this.storeDialog.fileTopData.sheetName = response.data.sheets[0].name;
              this.storeDialog.fileTopData.cols = response.data.sheets[0].cols;
              this.storeDialog.fileTopData.rows = response.data.sheets[0].rows;
              this.storeDialog.fileTopData.columnNames = response.data.sheets[0].data[0];
              this.storeDialog.fileTopData.columnTypes = response.data.sheets[0].types;
              this.storeDialog.fileTopData.data = response.data.sheets[0].transformed_data;
              this.storeDialog.fileTopData.originData = response.data.sheets[0].data;
          })
          this.storeDialog.open = true;
      },
      rowClassName({row, rowIndex}) {
        //把每一行的索引放进row.id
        row.id = rowIndex+2;
      },
      changeSheet(value) {
          this.storeDialog.loading = true;
          for (let sheet of this.storeDialog.sheets) {
              if (sheet.name === value) {
                  this.storeDialog.fileTopData.cols = sheet.cols;
                  this.storeDialog.fileTopData.rows = sheet.rows;
                  this.storeDialog.fileTopData.columnNames = sheet.data[0];
                  this.storeDialog.fileTopData.columnTypes = sheet.types;
                  this.storeDialog.fileTopData.data =sheet.transformed_data;
                  this.storeDialog.fileTopData.originData = sheet.data;
                  break;
              }
          }
          this.storeDialog.loading = false;
      },
      typeChange(value, index) {
          this.storeDialog.loading = true;
          let originData = this.storeDialog.fileTopData.originData.map(function(value) {return value[index]},this)
          console.log(originData)
          convertType({
              targetType: value,
              data: originData
          }).then(response => {
              console.log(response.data)
              for(var i = 0, len = this.storeDialog.fileTopData.data.length; i < len; i++) {
                this.storeDialog.fileTopData.data[i][index] = response.data[i];
              }
              this.storeDialog.loading = false;
          })
      },
      parseAndStore() {
        console.log(this.storeDialog.fileTopData);
        this.$refs["fileTopData"].validate(valid=>{
            if (valid) {
               let payload = {
                   fileId: this.storeDialog.fileTopData.fileId,
                   fileName: this.storeDialog.fileTopData.fileName, 
                   sheetName: this.storeDialog.fileTopData.sheetName,
                   titleLine: this.storeDialog.fileTopData.titleLine,
                   dataStartLine: this.storeDialog.fileTopData.dataStartLine,
                   handleException: this.storeDialog.fileTopData.handleException,
                   columnNames: this.storeDialog.fileTopData.originData[this.storeDialog.fileTopData.titleLine-1],
                   columnTypes: this.storeDialog.fileTopData.columnTypes
               };
               console.log(payload)
               storeFileData(payload).then(response=>{
                   if (response.code === 0) {
                        this.$modal.msgSuccess("数据内容存储成功");
                        this.getFileList();
                        this.storeDialog.open = false;
                   }
                   else {
                       this.$modal.msgError(response.message);
                   }
               })
            }    
        });
      }
    },
  }
</script>

<style lang="scss">
</style>